#coding=utf-8
#!/usr/bin/python 

import sys
import os
import os.path
import time

# 
#  从给出的文件中捞取具有关键字的行，并且输出到一个文件中
# E:python logFilter.py -i /Users/wesleyxiao/log.txt -o /Users/wesleyxiao/ -k hello
#  -i 指需要检索的文件
#  -o 输出的文件夹
#  -k 检索的关键字

def findKeyWordAndOutputFile(fullFileName,keyword,outputFile):
	"统计文件的行数"
	totleLineCount = 0
	writeFile = open(outputFile, "wb")
	lines = []
	try:
	    f = open(fullFileName, 'rU')
	    lines = f.readlines()
	except IOError as e:
	    print e
	else:
	    for line in lines:
	        totleLineCount=totleLineCount+1
	        if line.find(keyword)!=-1:
	        	print "文件:",fullFileName,"代码行:",totleLineCount,"内容",line
	        	# return line
	        	writeFile.write(line);
	finally:
	    f.close()
	writeFile.close()
	return totleLineCount

def findArgment(arg_prefix):
	"找到对应的参数 arg_prefix 为参数的前面的字符 如 -m"
	fileIdx = -1
	argIdx  = -1
	for idx in range(len(sys.argv)):
		arg = sys.argv[idx]
		if cmp(arg,arg_prefix)==0:
			argIdx = idx
		if argIdx!= -1 and argIdx+1==idx:
			# print "find arg",arg
			return arg
    
def timestamp_toString(stamp):  
    return time.strftime("%Y-%m-%d-%H:%M:%S", tiem.localtime(stamp)) 


# 主逻辑

inputDir = findArgment("-i")
outputDir = findArgment("-o")
keyword = findArgment("-k")



defaultInDir = "/Users/wesleyxiao/Documents/log/QQ2015-08-07.log"
defaultOutDir ="/Users/wesleyxiao/Documents/log"
defaultKeyword = "keyword"

defaultFile =time.strftime("%Y-%m-%d-%H%M%S_")+"output.txt"


if inputDir ==None:
	inputDir =  defaultInDir
if outputDir ==None:
	outputDir = defaultOutDir
if keyword ==None:
	keyword = defaultKeyword

print "开始搜索"


linecount = findKeyWordAndOutputFile(inputDir,keyword,outputDir+defaultFile)

print "***************结束搜索***************"
print "输入文件:",inputDir
print "输出文件:",outputDir+defaultFile
print "关键字:",keyword
print "搜索到的行数:",linecount